<?php

    /* postgres sql client class */
    class CPgSql
    {
		var $m_hDbms;		//dbms connection handler
		var $m_hQueryResult;	//query result handler 
		
		/* construct object of the class */
		/* return reference to created object */
		static function &GetInstance()
		{
			global $g_hObjects;
			static $m_hApp = NULL;
			
			if(!isset($m_hApp))
			{
			$m_hApp = new CPgSql();
			
			$g_hObjects[] = $m_hApp;
			
			$m_hApp->OnInit();
			}
			
			return $m_hApp;
		}
		
		/* initialization routines */
		function OnInit()
		{
			if(!function_exists('pg_connect'))
			{
			die("No PgSQL supported by this PHP instalation!");
			return false;
			}
		}
		
		/* called on script shutdown */
		function OnDestroy()
		{
			//$this->FreeResult();
			//$this->Close();
		}
		
		/* connection initialization */
		function Connect($szHost,$iPort,$szUser,$szPass,$szDbName)
		{
			$this->m_hDbms = pg_connect("host=$szHost port=$iPort user=$szUser password=$szPass dbname=$szDbName");
			
			if(!isset($this->m_hDbms))
			{
			return false;
			}
			
			return true;
		}
		
		/* closes connection to dbms */
		function Close()
		{
			if($this->m_hDbms)
			{
			pg_close($this->m_hDbms);
			}
		}
		
		/* obtain error message */
		function GetErrorMsg()
		{
			$ret = pg_last_error($this->m_hDbms);
			
			if($ret == FALSE)
			{
			return false;
			}
			else
			{
			return $ret;
			}
		}
		
		/* send query to the server */
		function Query($szQuery)
		{
			$this->m_hQueryResult = pg_query($this->m_hDbms,$szQuery);
			
			if($this->m_hQueryResult == FALSE)
			{
			return false;
			}
			
			return true;
		}
		
		/* get query handler */
		function GetQueryHandler()
		{
			return $this->m_hQueryResult;
		}
		
		/* free result memory */
		function FreeResult()
		{
			if(isset($this->m_hQueryResult))
			@pg_free_result($this->m_hQueryResult);
		}
		
		/* set encoding type */
		function SetEncoding($szType)
		{
			$query = "set client_encoding to '$szType' ";
			$this->Query($query);
		}
		
		/* return rows number in result */
		function GetResultCount()
		{
			return pg_num_rows($this->m_hQueryResult);
		}
		
		/* get row from query */
		function GetResultAsRow()
		{
			return @pg_fetch_assoc($this->m_hQueryResult);
		}
		
		/* get result row as numerated and associated array - both array & association array are supported */
		function GetResultAsArray()
		{
			return @pg_fetch_array($this->m_hQueryResult,0,PGSQL_BOTH);
		}
		
		/* get whole result from query */
		function GetResult()
		{
			$result = array();
			
			while($entry = @pg_fetch_assoc($this->m_hQueryResult))
			{
			$result[] = $entry;
			}
			
			return $result;
		}
		
		/* show all tables */
		function ShowTables()
		{
			$query = "select * from pg_tables";
			
			$this->Query($query);
		}
		
		/* show databases */
		function ShowDatabases()
		{
			$query = "select * from pg_database";
			
			$this->Query($query);
		}
    }

?>